package com.kingtone.rongji.network;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ByteArrayEntity;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.biz.CommonMessage;
import com.kingtone.rongji.biz.User;
import com.kingtone.rongji.biz.UserCounts;
import com.kingtone.rongji.tool.AppRestClient;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class UserRequest extends CommonRequest {

	public void login(String username, String password,
			final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("username", username);
		params.put("pwd", password);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.LOGIN_URL, params,
				this.createCommonHandler(restClient, true));
	}

	public void register(String username, String password, String cellphone,
			final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("CellPhone", cellphone);
		params.put("Email", username);
		params.put("Password", password);
		params.put("UserName", username);
		params.setUseJsonStreamer(true);
		AppRestClient.post(RongJiRestClient.REGISTER_URL, params,
				this.createCommonHandler(restClient, true));
	}
	
	public void loginByThirdPart(String password, String email, String realName, String icon, int gender,
			final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("username", email);
		params.put("pwd", password);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.LOGIN_URL, params,
				new ThirdLoginHandler(restClient, password, email, realName, icon, gender));
	}
	
	public void registerByThirdPart(String password, String email, String realName, String icon, int gender,
			final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("HeadImgUrl", icon);
		params.put("Gender", gender);
		params.put("Password", password);
		params.put("UserName", email);
		params.put("RealName", realName);
		params.put("Email", email);
		params.put("EnableEmail", false);
		params.put("ThirdUserId", password);
		params.setUseJsonStreamer(true);
		AppRestClient.post(RongJiRestClient.REGISTER_THIRDPART_URL, params,
				this.createCommonHandler(restClient, true));
	}

	public void update(User user, String username, String email,
			String birthDate, String realName, String cellphone, int gender,
			final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("CellPhone", cellphone);
		params.put("Email", email);
		if(birthDate != null && birthDate.trim().length() > 0)
		{
			params.put("BirthDate", birthDate);
		}
		params.put("RealName", realName);
		params.put("UserName", username);
		params.put("UserId", user.getUserId());
		params.put("Gender", gender);
		
		//不变属性
		params.put("UserId", user.getUserId());
		params.put("RegionId", user.getRegionId());
		params.put("Address", user.getAddress());
		params.put("QQ", user.getUserId());
		params.put("MSN", user.getUserId());
		params.put("TelePhone", user.getUserId());
		params.put("UserRank", user.getUserRank());
		params.put("UserType", user.getUserType());
		params.put("ThirdUserId", user.getThirdUserId());
		params.put("HeadImgUrl", user.getHeadImgUrl());
		params.put("PickUpAddress", user.getPickUpAddress());
		
		params.setUseJsonStreamer(true);
		AppRestClient.post(RongJiRestClient.REGISTER_URL, params,
				this.createCommonHandler(restClient, true));
	}

	public void getUserInfo(String userId, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("UserId", userId);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.USER_INFO_URL, params, new UserInfoHandler(
				restClient, true));
	}
	
	public void getUserCounts(String userId, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("UserId", userId);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.USER_COUNTS_URL, params, new UserCountHandler(restClient));
	}
	
	public void getUserInfoByName(String userName, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("UserName", userName);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.USER_INFO_BY_NAME_URL, params, new UserInfoHandler(
				restClient, false));
	}
	
	public void sendPasswordByEmail(String userName, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("UserName", userName);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.USER_INFO_URL, params, new UserInfoHandler(
				restClient, false));
	}

	public void changPwdStep1(Context context, String userId, String newPassword,
			String oldPassword, String token, final IRequestHandler restClient) throws UnsupportedEncodingException {
		List<String> list = new ArrayList<String>();
		list.add(oldPassword);
		list.add(newPassword);
		String json = new Gson().toJson(list);
		ByteArrayEntity entity = new ByteArrayEntity(json.getBytes());
		entity.setContentType("application/json");
		AppRestClient.postEntity(context, RongJiRestClient.USER_ENCODE_PWD_URL, entity,
				new PwdHandler(restClient, true, userId, token));
	}
	
	public void changPwdStep2(String userId, String newPassword,
			String oldPassword, String token, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("Password", newPassword);
		params.put("OldPassword", oldPassword);
		params.put("UserId", userId);
		if(token != null && token.trim().length() > 0)
		{
			params.put("PublicToken", token);
		}
		else
		{
			params.put("CurrentUserId", userId);
		}
		params.setUseJsonStreamer(true);
		AppRestClient.post(RongJiRestClient.USER_CHANG_PWD_URL, params,
				this.createCommonHandler(restClient, true));
	}
	
	public void resetByEmail(String userName, String email, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("UserName", userName);
		params.put("email", email);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.RESET_EMAIL_URL, params,
				this.createCommonHandler(restClient, true));
	}

	public void getVerifyCode(int userId, String cellPhone, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("userId", userId);
		params.put("cellPhone", cellPhone);
		params.put("SMSType", 1);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.SMS_VERIFY_URL, params,
				this.createCommonHandler(restClient, true));
	}
	
	public void checkVerifyCode(int userId, String smsCode, final IRequestHandler restClient) {
		RequestParams params = new RequestParams();
		params.put("userId", userId);
		params.put("SMSCode", smsCode);
		params.put("SMSType", 1);
		params.put("appKey", AppRestClient.API_KEY);
		AppRestClient.get(RongJiRestClient.SMS_CHECK_URL, params,
				this.createCommonHandler(restClient, true));
	}
	
	class ThirdLoginHandler extends BaseJsonHttpResponseHandler {

		private IRequestHandler restClient;

		private String password;
		
		private String email;
		
		private String realName;
		
		private String icon;
		
		private int gender;
		
		public ThirdLoginHandler(IRequestHandler restClient, String password, String email, String realName, String icon, int gender) {
			super();
			this.restClient = restClient;
			this.password = password;
			this.email = email;
			this.realName = realName;
			this.icon = icon;
			this.gender = gender;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable throwable,
				String arg3, Object arg4) {
			// TODO Auto-generated method stub
			if (null != throwable) {
				throwable.printStackTrace();
			}
			restClient.onNetworkFailure();
		}

		@Override
		public void onSuccess(int statusCode, Header[] arg1,
				String responseString, Object arg3) {
			if (statusCode == HttpStatus.SC_OK) {
				try {
					CommonMessage common = (CommonMessage) parseResponse(responseString, false);
					if (common != null) {
						if (common.getStatus()) {
							restClient.onBussinessSuccess(common);
							return;
						} else{
							registerByThirdPart(password, email, realName, icon, gender, restClient);
							return;
						}
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		@Override
		protected Object parseResponse(String rawJsonData, boolean isFailure)
				throws Throwable {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			JsonParser parser = new JsonParser();
			JsonElement elment = parser.parse(rawJsonData);
			CommonMessage common = gson.fromJson(elment, CommonMessage.class);
			return common;
		}
	}
	
	class PwdHandler extends BaseJsonHttpResponseHandler {

		private IRequestHandler restClient;

		private boolean showProgress;
		
		private String userId;
		
		private String token;

		public PwdHandler(IRequestHandler restClient, boolean showProgress, String userId, String token) {
			super();
			this.restClient = restClient;
			this.showProgress = showProgress;
			this.userId = userId;
			this.token = token;
		}

		@Override
		public void onStart() {
			if (showProgress) {
				RongJiUtils.showEmptyProgress(restClient.getContext());
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable throwable,
				String arg3, Object arg4) {
			// TODO Auto-generated method stub
			if (null != throwable) {
				throwable.printStackTrace();
			}
			if (showProgress) {
				RongJiUtils.dismissProgress();
			}
			restClient.onNetworkFailure();
		}

		@Override
		public void onSuccess(int statusCode, Header[] arg1,
				String responseString, Object arg3) {
			if (statusCode == HttpStatus.SC_OK) {
				try {
					String[] arrays = parseResponse(responseString, false);
					if (arrays != null && arrays.length == 2) {
						changPwdStep2(userId, arrays[0], arrays[1], token, restClient);
						return;
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			restClient.onNetworkFailure();
		}

		@Override
		protected String[] parseResponse(String rawJsonData, boolean isFailure)
				throws Throwable {
			// TODO Auto-generated method stub
			JsonParser parser = new JsonParser();
			JsonElement elment = parser.parse(rawJsonData);
			String[] arrays = new String[2];
			JsonArray jsonArray = elment.getAsJsonArray();
			arrays[0] = jsonArray.get(0).toString().replaceAll("\"", "");
			arrays[1] = jsonArray.get(1).toString().replaceAll("\"", "");
			return arrays;
		}
	}
	
	class UserCountHandler extends BaseJsonHttpResponseHandler {

		private IRequestHandler restClient;

		public UserCountHandler(IRequestHandler restClient) {
			super();
			this.restClient = restClient;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable throwable,
				String arg3, Object arg4) {
			// TODO Auto-generated method stub
			if (null != throwable) {
				throwable.printStackTrace();
			}
		}

		@Override
		public void onSuccess(int statusCode, Header[] arg1,
				String responseString, Object arg3) {
			if (statusCode == HttpStatus.SC_OK) {
				try {
					UserCounts userCounts = parseResponse(responseString, false);
					if (userCounts != null) {
						restClient.onBussinessSuccess(userCounts);
						return;
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		@Override
		protected UserCounts parseResponse(String rawJsonData, boolean isFailure)
				throws Throwable {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			JsonParser parser = new JsonParser();
			JsonElement elment = parser.parse(rawJsonData);
			UserCounts userCounts = gson.fromJson(elment, UserCounts.class);
			return userCounts;
		}
	}
	
	class UserInfoHandler extends BaseJsonHttpResponseHandler {

		private IRequestHandler restClient;

		private boolean showProgress;

		public UserInfoHandler(IRequestHandler restClient, boolean showProgress) {
			super();
			this.restClient = restClient;
			this.showProgress = showProgress;
		}

		@Override
		public void onStart() {
			if (showProgress) {
				RongJiUtils.showEmptyProgress(restClient.getContext());
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, Throwable throwable,
				String arg3, Object arg4) {
			// TODO Auto-generated method stub
			if (null != throwable) {
				throwable.printStackTrace();
			}
			if (showProgress) {
				RongJiUtils.dismissProgress();
			}
			restClient.onNetworkFailure();
		}

		@Override
		public void onSuccess(int statusCode, Header[] arg1,
				String responseString, Object arg3) {
			if (showProgress) {
				RongJiUtils.dismissProgress();
			}

			if (statusCode == HttpStatus.SC_OK) {
				try {
					User user = parseResponse(responseString, false);
					if (user != null) {
						restClient.onBussinessSuccess(user);
						return;
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			restClient.onBussinessError("该用户不存在，请确认后再重新输入!");
		}

		@Override
		protected User parseResponse(String rawJsonData, boolean isFailure)
				throws Throwable {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			JsonParser parser = new JsonParser();
			JsonElement elment = parser.parse(rawJsonData);
			User user = gson.fromJson(elment, User.class);
			return user;
		}
	}
}
